<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="题目名称" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入题目名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherName">
          <el-input
            v-model="queryParams.teacherName"
            placeholder="请输入教师姓名"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="难度等级" prop="difficulty">
          <el-select v-model="queryParams.difficulty" placeholder="请选择" clearable style="width: 120px">
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>
        <el-form-item label="技术标签" prop="tags">
          <el-input
            v-model="queryParams.tags"
            placeholder="请输入技术标签"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <i class="el-icon-document stats-icon" style="color: #409EFF;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ total }}</div>
              <div class="stats-label">可选题目</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <i class="el-icon-user stats-icon" style="color: #67C23A;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ teacherCount }}</div>
              <div class="stats-label">发布教师</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <i class="el-icon-warning stats-icon" style="color: #E6A23C;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ availableCount }}</div>
              <div class="stats-label">有剩余名额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card" @click.native="goToMyApplications">
          <div class="stats-content">
            <i class="el-icon-star-off stats-icon" style="color: #F56C6C;"></i>
            <div class="stats-text">
              <div class="stats-value">
                {{ myApplicationCount }}
                <el-tag v-if="isAccepted" type="success" size="mini" style="margin-left: 8px;">已录取</el-tag>
              </div>
              <div class="stats-label">我的志愿</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 状态提示横幅 -->
    <el-alert
      v-if="isAccepted"
      type="success"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    >
      <template slot="title">
        <strong>🎉 恭喜！您已被录取</strong>
      </template>
      <div style="font-size: 13px; margin-top: 5px;">
        您已成功被录取，无需再申请其他题目。如需更换题目，请使用"换题申请"功能。
      </div>
    </el-alert>

    <el-alert
      v-else-if="hasFirstPriority && hasSecondPriority"
      type="warning"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    >
      <template slot="title">
        <strong>⚠️ 志愿已满</strong>
      </template>
      <div style="font-size: 13px; margin-top: 5px;">
        您的第一志愿和第二志愿均已填报，暂时无法申请新题目。如需更换，请先取消已有申请。
      </div>
    </el-alert>

    <!-- 题目列表 -->
    <el-row :gutter="20" v-loading="loading">
      <el-col :span="8" v-for="topic in topicList" :key="topic.topicId">
        <el-card class="topic-card" shadow="hover">
          <!-- 头部：标题和标签 -->
          <div class="topic-header">
            <h3 class="topic-title">{{ topic.title }}</h3>
            <div class="topic-tags">
              <el-tag :type="getDifficultyType(topic.difficulty)" size="mini">{{ topic.difficulty }}</el-tag>
              <el-tag
                type="info"
                size="mini"
                :class="getRemainingClass(topic)"
              >
                {{ topic.currentStudents || 0 }}/{{ topic.maxStudents }}
              </el-tag>
            </div>
          </div>

          <!-- 教师信息 -->
          <div class="topic-teacher">
            <i class="el-icon-user"></i>
            <span>{{ topic.teacherName }}</span>
          </div>

          <!-- 描述 -->
          <div class="topic-description">
            {{ topic.description | ellipsis(80) }}
          </div>

          <!-- 技术标签 -->
          <div class="topic-tech-tags" v-if="topic.tags && topic.tags !== '[]'">
            <el-tag
              v-for="tag in parseTags(topic.tags).slice(0, 4)"
              :key="tag"
              size="mini"
              type="info"
              effect="plain"
            >{{ tag }}</el-tag>
            <span v-if="parseTags(topic.tags).length > 4" class="more-tags">...</span>
          </div>

          <!-- 底部：操作按钮 -->
          <!-- 状态提示 -->
          <div class="topic-status" v-if="isTopicPendingModification(topic)">
            <i class="el-icon-warning"></i>
            <span>该题目正在修改中，请谨慎选择</span>
          </div>

          <div class="topic-footer">
            <el-button
              type="primary"
              size="small"
              :disabled="!canApplyTopic(topic)"
              @click="handleApply(topic)"
            >
              {{ isTopicFull(topic) ? '已满员' : '报名' }}
            </el-button>
            <el-button type="text" size="small" @click="handleViewDetail(topic)">
              查看详情
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 空状态 -->
    <el-empty v-if="!loading && topicList.length === 0" description="暂无可选题目"></el-empty>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 题目详情对话框（原版，只能查看） -->
    <topic-detail ref="topicDetail" @apply="handleApplyFromDetail" />
    
    <!-- 报名对话框（简单，用于报名） -->
    <apply-dialog ref="applyDialog" @success="handleApplySuccess" />
  </div>
</template>

<script>
import { listApprovedTopic } from "@/api/system/topic";
import { getMyStats, listMyApplications } from "@/api/system/application";
import TopicDetail from "./TopicDetail"; // 详情组件
import ApplyDialog from "./ApplyDialog"; // 报名对话框

export default {
  name: "StudentTopic",
  components: {
    TopicDetail,
    ApplyDialog
  },
  filters: {
    ellipsis(value, length) {
      if (!value) return '';
      if (value.length <= length) return value;
      return value.substring(0, length) + '...';
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 题目列表
      topicList: [],
      // 教师数量
      teacherCount: 0,
      // 有剩余名额数量
      availableCount: 0,
      // 我的志愿数量
      myApplicationCount: 0,
      // 是否已被录取
      isAccepted: false,
      // 第一志愿是否已填
      hasFirstPriority: false,
      // 第二志愿是否已填
      hasSecondPriority: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        title: null,
        teacherName: null,
        difficulty: null,
        tags: null
      }
    };
  },
  created() {
    this.getList();
    this.getMyApplicationCount();
  },
  methods: {
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listApprovedTopic(this.queryParams).then(response => {
        this.topicList = response.rows;
        this.total = response.total;
        this.loading = false;
        
        // 统计教师数量
        const teacherIds = new Set(this.topicList.map(t => t.teacherId));
        this.teacherCount = teacherIds.size;
        
        // 统计有剩余名额的题目
        this.availableCount = this.topicList.filter(t => !this.isTopicFull(t)).length;
      });
    },
    
    /** 获取我的志愿数量和状态 */
    getMyApplicationCount() {
      // 获取统计数量
      getMyStats().then(response => {
        this.myApplicationCount = response.data;
      });
      
      // 获取详细的申请列表来判断状态
      listMyApplications().then(response => {
        const applications = response.data || [];
        
        // 判断是否已被录取
        this.isAccepted = applications.some(app => app.status === '已录取');
        
        // 判断第一志愿是否已填（包括待审核、已录取状态）
        this.hasFirstPriority = applications.some(app => 
          app.priority === 1 && ['待审核', '已录取'].includes(app.status)
        );
        
        // 判断第二志愿是否已填
        this.hasSecondPriority = applications.some(app => 
          app.priority === 2 && ['待审核', '已录取'].includes(app.status)
        );
      });
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    /** 查看详情 - 使用原版详情组件 */
    handleViewDetail(topic) {
      this.$refs.topicDetail.openDialog(topic.topicId);
    },
    
    /** 报名 - 使用简单的报名对话框 */
    handleApply(topic) {
      // 检查是否已被录取
      if (this.isAccepted) {
        this.$modal.msgWarning("您已被录取，无法继续申请其他题目");
        return;
      }
      
      // 检查题目是否已满
      if (this.isTopicFull(topic)) {
        this.$modal.msgWarning("该题目已满员");
        return;
      }
      
      // 检查志愿是否已满
      if (this.hasFirstPriority && this.hasSecondPriority) {
        this.$modal.msgWarning("您的一二志愿均已填报，无法继续申请");
        return;
      }
      
      // 打开报名对话框
      this.$refs.applyDialog.open(topic);
    },
    
    /** 从详情对话框报名 */
    handleApplyFromDetail(topic) {
      this.handleApply(topic);
    },
    
    /** 申请成功回调 */
    handleApplySuccess() {
      this.getList();
      this.getMyApplicationCount();
    },
    
    /** 跳转到我的志愿 */
    goToMyApplications() {
      this.$router.push('/system/application/student');
    },
    
    /** 判断题目是否已满 */
    isTopicFull(topic) {
      return topic.currentStudents >= topic.maxStudents;
    },
    
    /** 判断是否可以申请题目 */
    canApplyTopic(topic) {
      // 如果已被录取，不能再申请
      if (this.isAccepted) {
        return false;
      }
      
      // 如果题目已满，不能申请
      if (this.isTopicFull(topic)) {
        return false;
      }
      
      // 如果一二志愿都已填满，不能申请
      if (this.hasFirstPriority && this.hasSecondPriority) {
        return false;
      }
      
      return true;
    },

    /** 判断题目是否处于修改审核中 */
    isTopicPendingModification(topic) {
      return topic.auditStatus === '修改待审核' && topic.hasPendingChanges === 1;
    },
    
    /** 解析标签 */
    parseTags(tags) {
      if (!tags) return [];
      try {
        return JSON.parse(tags);
      } catch (e) {
        return [];
      }
    },
    
    /** 难度等级标签类型 */
    getDifficultyType(difficulty) {
      const map = {
        '简单': 'success',
        '中等': '',
        '困难': 'danger'
      };
      return map[difficulty] || 'info';
    },
    
    /** 剩余名额样式 */
    getRemainingClass(topic) {
      const remaining = topic.maxStudents - (topic.currentStudents || 0);
      if (remaining === 0) return 'tag-full';
      if (remaining <= 2) return 'tag-warning';
      return '';
    }
  }
};
</script>

<style scoped lang="scss">
.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  font-size: 48px;
  margin-right: 20px;
}

.stats-text {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.topic-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
  height: 320px;
  display: flex;
  flex-direction: column;
  position: relative;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  ::v-deep .el-card__body {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}

.pending-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
}

.topic-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.topic-title {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin: 0;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.topic-tags {
  display: flex;
  gap: 5px;
  margin-left: 10px;
  
  .el-tag {
    flex-shrink: 0;
  }
}

.tag-warning {
  background-color: #FDF6EC;
  border-color: #F5DAB1;
  color: #E6A23C;
}

.tag-full {
  background-color: #FEF0F0;
  border-color: #FAB6B6;
  color: #F56C6C;
}

.topic-teacher {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
  
  i {
    margin-right: 5px;
  }

.topic-modification-tip {
  background-color: #FFF7E6;
  border-left: 3px solid #E6A23C;
  color: #E6A23C;
  font-size: 12px;
  padding: 8px 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  
  i {
    margin-right: 5px;
    font-size: 14px;
  }
}
}

.topic-description {
  color: #909399;
  font-size: 13px;
  line-height: 1.6;
  margin-bottom: 10px;
  flex: 1;
  overflow: hidden;
}

.topic-tech-tags {
  margin-bottom: 15px;
  min-height: 24px;
  
  .el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }
  
  .more-tags {
    color: #909399;
    font-size: 12px;
  }
}

.topic-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #EBEEF5;
}

.topic-status {
  padding: 8px 12px;
  margin-bottom: 10px;
  background-color: #FDF6EC;
  border: 1px solid #F5DAB1;
  border-radius: 4px;
  color: #E6A23C;
  font-size: 13px;
  display: flex;
  align-items: center;
  
  i {
    margin-right: 6px;
    font-size: 14px;
  }
}
</style>